<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList"
      :search-params="searchParams"
    ></SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-tabs v-model="activeTab" @tab-click="handleTabChange">
            <el-tab-pane label="全部申请" name="all"></el-tab-pane>
            <el-tab-pane label="待审批" name="pending"></el-tab-pane>
            <el-tab-pane label="已批准" name="approved"></el-tab-pane>
            <el-tab-pane label="已完成" name="completed"></el-tab-pane>
            <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="申请编号" prop="code" width="120" />
            <el-table-column label="物资/设备" prop="idle_item.name" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="类型" align="center" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.idle_item.type === '物资'" type="success">物资</el-tag>
                <el-tag v-else-if="scope.row.idle_item.type === '设备'" type="primary">设备</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="申请数量" align="center" prop="quantity" width="100" />
            <el-table-column label="申请人" prop="applicant_name" width="120" />
            <el-table-column label="申请人电话" prop="applicant_phone" width="120" />
            <el-table-column label="申请单位" prop="applicant_unit" width="150" :show-overflow-tooltip="true" />
            <el-table-column label="申请时间" prop="apply_time" width="160" />
            <el-table-column label="状态" align="center" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 'pending'" type="warning">待审批</el-tag>
                <el-tag v-else-if="scope.row.status === 'approved'" type="success">已批准</el-tag>
                <el-tag v-else-if="scope.row.status === 'completed'" type="primary">已完成</el-tag>
                <el-tag v-else-if="scope.row.status === 'cancelled'" type="info">已取消</el-tag>
                <el-tag v-else-if="scope.row.status === 'rejected'" type="danger">已拒绝</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="220px">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status === 'pending'" type="text" @click="onApprove(scope.row)">批准</el-button>
                <el-button v-if="scope.row.status === 'pending'" type="text" style="color: #F56C6C" @click="onReject(scope.row)">拒绝</el-button>
                <el-button v-if="scope.row.status === 'approved'" type="text" @click="onComplete(scope.row)">完成调拨</el-button>
                <el-button v-if="scope.row.status === 'pending'" type="text" style="color: #909399" @click="onCancel(scope.row)">取消</el-button>
                <el-button type="text" @click="onView(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog title="调拨申请详情" :visible.sync="detailVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请编号">{{ detail.code }}</el-descriptions-item>
        <el-descriptions-item label="物资/设备名称">{{ detail.idle_item?.name }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag v-if="detail.idle_item?.type === '物资'" type="success">物资</el-tag>
          <el-tag v-else-if="detail.idle_item?.type === '设备'" type="primary">设备</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detail.idle_item?.specification }}</el-descriptions-item>
        <el-descriptions-item label="申请数量">{{ detail.quantity }} {{ detail.idle_item?.unit }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detail.status === 'pending'" type="warning">待审批</el-tag>
          <el-tag v-else-if="detail.status === 'approved'" type="success">已批准</el-tag>
          <el-tag v-else-if="detail.status === 'completed'" type="primary">已完成</el-tag>
          <el-tag v-else-if="detail.status === 'cancelled'" type="info">已取消</el-tag>
          <el-tag v-else-if="detail.status === 'rejected'" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请人">{{ detail.applicant_name }}</el-descriptions-item>
        <el-descriptions-item label="申请人电话">{{ detail.applicant_phone }}</el-descriptions-item>
        <el-descriptions-item label="申请单位">{{ detail.applicant_unit }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detail.apply_time }}</el-descriptions-item>
        <el-descriptions-item label="审批人" v-if="detail.approver_name">{{ detail.approver_name }}</el-descriptions-item>
        <el-descriptions-item label="审批时间" v-if="detail.approve_time">{{ detail.approve_time }}</el-descriptions-item>
        <el-descriptions-item label="完成时间" v-if="detail.complete_time">{{ detail.complete_time }}</el-descriptions-item>
        <el-descriptions-item label="取消时间" v-if="detail.cancel_time">{{ detail.cancel_time }}</el-descriptions-item>
        <el-descriptions-item label="申请原因" :span="2">{{ detail.reason }}</el-descriptions-item>
        <el-descriptions-item label="审批意见" :span="2" v-if="detail.approve_remark">{{ detail.approve_remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 审批弹窗 -->
    <el-dialog :title="approveDialogTitle" :visible.sync="approveDialogVisible" width="500px">
      <el-form :model="approveForm" :rules="approveRules" ref="approveForm" label-width="100px">
        <el-form-item label="审批意见" prop="remark">
          <el-input type="textarea" v-model="approveForm.remark" placeholder="请输入审批意见" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitApprove">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http } from "@/api";
import SearchForm from "@/components/SearchForm";

export default {
  name: "IdleTransfer",
  components: {
    SearchForm
  },
  mixins: [crud],
  data() {
    return {
      searchList: [
        { label: '申请编号', prop: 'code', name: 'input' },
        { label: '物资/设备名称', prop: 'item_name', name: 'input' },
        {
          label: '类型',
          prop: 'item_type',
          name: 'select',
          options: [
            { label: '物资', value: '物资' },
            { label: '设备', value: '设备' }
          ]
        },
        { label: '申请人', prop: 'applicant_name', name: 'input' },
        {
          label: '状态',
          prop: 'status',
          type: 'select',
          options: [
            { label: '待审批', value: 'pending' },
            { label: '已批准', value: 'approved' },
            { label: '已完成', value: 'completed' },
            { label: '已取消', value: 'cancelled' },
            { label: '已拒绝', value: 'rejected' }
          ]
        }
      ],
      searchParams: {
        code: '',
        item_name: '',
        item_type: '',
        applicant_name: '',
        status: ''
      },

      // 表格相关
      request: http.idleTransfer,
      activeTab: 'all',

      // 详情弹窗
      detailVisible: false,
      detail: {},

      // 审批弹窗
      approveDialogVisible: false,
      approveDialogTitle: '审批调拨申请',
      approveType: 'approve', // approve, reject
      approveForm: {
        id: '',
        remark: ''
      },
      approveRules: {
        remark: [
          { required: true, message: '请输入审批意见', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleTabChange() {
      // 根据选中的标签页筛选数据
      if (this.activeTab === 'all') {
        this.searchParams.status = '';
      } else {
        this.searchParams.status = this.activeTab;
      }
      this.initData();
    },

    onView(row) {
      http.idleTransfer.read(row.id).then(res => {
        this.detail = res.data;
        this.detailVisible = true;
      });
    },

    onApprove(row) {
      this.approveDialogTitle = '批准调拨申请';
      this.approveType = 'approve';
      this.approveForm = {
        id: row.id,
        remark: ''
      };
      this.approveDialogVisible = true;
    },

    onReject(row) {
      this.approveDialogTitle = '拒绝调拨申请';
      this.approveType = 'reject';
      this.approveForm = {
        id: row.id,
        remark: ''
      };
      this.approveDialogVisible = true;
    },

    onComplete(row) {
      this.$confirm('确认完成该调拨申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.idleTransfer.complete(row.id).then(() => {
          this.$message.success('操作成功');
          this.initData();
        }).catch(error => {
          this.$message.error(error.message || '操作失败');
        });
      }).catch(() => {});
    },

    onCancel(row) {
      this.$confirm('确认取消该调拨申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.idleTransfer.cancel(row.id).then(() => {
          this.$message.success('取消成功');
          this.initData();
        }).catch(error => {
          this.$message.error(error.message || '取消失败');
        });
      }).catch(() => {});
    },

    submitApprove() {
      this.$refs.approveForm.validate(valid => {
        if (valid) {
          const id = this.approveForm.id;
          const remark = this.approveForm.remark;

          if (this.approveType === 'approve') {
            http.idleTransfer.approve(id, { remark }).then(() => {
              this.$message.success('批准成功');
              this.approveDialogVisible = false;
              this.initData();
            }).catch(error => {
              this.$message.error(error.message || '批准失败');
            });
          } else if (this.approveType === 'reject') {
            http.idleTransfer.reject(id, { remark }).then(() => {
              this.$message.success('拒绝成功');
              this.approveDialogVisible = false;
              this.initData();
            }).catch(error => {
              this.$message.error(error.message || '拒绝失败');
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.table-handle {
  margin-bottom: 20px;
}
.table-box {
  margin-bottom: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
</style>
